<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let chart = null;

function initChart() {
  if (!chartRef.value) return;
  
  // 销毁旧图表
  if (chart) {
    chart.dispose();
  }
  
  // 根据主题初始化
  chart = echarts.init(chartRef.value, props.theme);
  
  // 根据主题设置不同配色
  const colors = props.theme === 'dark' 
    ? ['#177ddc', '#49aa19', '#d89614'] 
    : ['#1890ff', '#52c41a', '#fa8c16'];
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: props.theme === 'dark' ? '#177ddc' : '#6a7985'
        }
      }
    },
    legend: {
      data: ['采购入库', '生产入库', '退货入库']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData.months
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '采购入库',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          opacity: 0.6
        },
        emphasis: {
          focus: 'series'
        },
        data: props.chartData.purchase,
        color: colors[0],
        smooth: true,
        symbolSize: 6,
        animationDuration: 2000
      },
      {
        name: '生产入库',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          opacity: 0.6
        },
        emphasis: {
          focus: 'series'
        },
        data: props.chartData.production,
        color: colors[1],
        smooth: true,
        symbolSize: 6,
        animationDuration: 2000,
        animationDelay: 300
      },
      {
        name: '退货入库',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          opacity: 0.6
        },
        emphasis: {
          focus: 'series'
        },
        data: props.chartData.return,
        color: colors[2],
        smooth: true,
        symbolSize: 6,
        animationDuration: 2000,
        animationDelay: 600
      }
    ],
    animationEasing: 'quadraticOut'
  };
  
  chart.setOption(option);
}

function resizeChart() {
  chart && chart.resize();
}

// 监听主题变化
watch(() => props.theme, () => {
  initChart();
});

// 监听数据变化
watch(() => props.chartData, () => {
  initChart();
}, { deep: true });

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  chart && chart.dispose();
  window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style> 